package com.gupt.youhd.service.impl;/*
@author name
@data 2023/4/22-14:02
*/

import com.gupt.youhd.common.StringConstant;
import com.gupt.youhd.exception.BusinessException;
import com.gupt.youhd.mapper.SchoolMapper;
import com.gupt.youhd.mapper.StuTeaMapper;
import com.gupt.youhd.mapper.UserMapper;
import com.gupt.youhd.entity.School;
import com.gupt.youhd.entity.StuOrTea;
import com.gupt.youhd.entity.User;
import com.gupt.youhd.qo.RegisterQo;
import com.gupt.youhd.service.RegisterService;
import com.gupt.youhd.util.RedisUtils;
import com.gupt.youhd.util.TokenGenerator;
import com.gupt.youhd.util.VerifyCodeUtil;
import com.gupt.youhd.util.YouHDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;

@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    SchoolMapper schoolMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    StuTeaMapper stuTeaMapper;


    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取验证码，并存入redis
     * @return
     */
    @Override
    public Map<String, String> getCaptcha(String userName) {

        //校验当前用户是否有输入用户名（手机号码
        if(userName == null || userName.equals("")){
            throw new BusinessException("请输入手机号码");
        }

        boolean isOk = YouHDUtils.isMobileNumberValid(userName);
        if(!isOk){
            throw new BusinessException("当前手机号码不规范");
        }

        Map<String, String> map = VerifyCodeUtil.generateVerifyCode();
        String code = map.get("code");
        String uuid = map.get("uuid");
        //保证redis中的key唯一性， 在添加前缀去辨别当前的key
        redisUtils.set(StringConstant.LOGIN_CAPTCHA_CODE+uuid,code,StringConstant.LOGIN_CAPTCHA_CODE_EXPIRE_TIME);

        //将map中的img地址删除
        map.remove("img");

        log.info("当前系统生成验证码：{}",code);

        return map;
    }


    //用户注册
    @Override
    public String register(RegisterQo qo) {

        //校验注册校名规范性
        School school = retrieveSchoolBySchoolName(qo.getSchoolName());

        if(school == null){
            throw new BusinessException("暂不支持该学校");
        }
        log.info("查询校名结果：{}",school);

        //校验用户名规范
        boolean numberValid = YouHDUtils.isMobileNumberValid(qo.getUsername());
        if(!numberValid){
            throw new BusinessException("请输入正确的手机号码");
        }

        //校验注册用户名是否存在
        User user = retrieveUserByUsername(qo.getUsername());
        if(user != null){
            throw new BusinessException("该用户已存在");
        }

        //校验确认密码是否一致
        if(qo.getPwd() == null || qo.getPassword() == null){
            throw new BusinessException("请输入密码");
        }

        if(!qo.getPwd().equals(qo.getPassword())){
            throw new BusinessException("前后密码不一致");
        }

        //校验验证码是否正确
        String code = qo.getCode();
        String trueCode = redisUtils.get(StringConstant.LOGIN_CAPTCHA_CODE + qo.getUuid());

        if(trueCode == null){
            throw new BusinessException("验证码失效,请重新获取");
        }

        //校验验证码一致性
        if(!VerifyCodeUtil.verification(trueCode,code,true)){
            throw new BusinessException("验证码错误");
        }

        //md5加密处理密码
        String password = DigestUtils.md5DigestAsHex(qo.getPassword().getBytes());

        //将用户信息插入对应表
        User userInfo = new User();
        userInfo.setUsername(qo.getUsername());
        userInfo.setPassword(password);
        userInfo.setSchoolName((qo.getSchoolName()));

        int status = saveUserMsg(userInfo, qo.getSchoolName());
        if(status <= 0){
            throw new BusinessException("注册失败");
        }

        return "注册成功";
    }

    @Override
    public School retrieveSchoolBySchoolName(String SchoolName) {
        School school = schoolMapper.retrieveSchoolBySchoolName(SchoolName);
        return school;
    }

    @Override
    public User retrieveUserByUsername(String username) {
        User user = userMapper.retrieveUserByUsername(username);
        return user;
    }


    @Override
    public int saveUserMsg(User user,String schoolName) {
        int i = userMapper.insertUser(user);
        log.info("插入user表数据条数：{}",i);

        //查询当前插入id，再插入到stuOrTea表中
        User userInfo = userMapper.retrieveUserByUsername(user.getUsername());

        //查询当前学校名的学校id
        School school = schoolMapper.retrieveSchoolBySchoolName(schoolName);
        int schoolId = school.getSchoolId();

        StuOrTea stu = new StuOrTea();
        stu.setUserId(userInfo.getUserId());
        stu.setSchoolId(schoolId);
        //设置默认用户名
        stu.setName("youhdUser_"+ TokenGenerator.generateToken());
        int j = stuTeaMapper.insertStuMsg(stu);//信息插入学生表
        log.info("插入student_teacher表数据条数：{}",j);
        return i+j;
    }
}
